package com.tegtech.starter.validator;

import java.util.List;
import java.util.stream.Collectors;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.tegtech.common.utils.spring.SpringUtils;
import com.tegtech.module.dict.DictValCache;
import com.tegtech.module.dict.domain.DictVal;
import com.tegtech.starter.validator.annotation.Dict;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * Dict注解校验实现类
 * @Author Jun
 * @date 2020年5月2日 下午2:10:49
 */
public class DictValidator implements ConstraintValidator<Dict, Object> {

	private String type = "";
	
	@Override
    public void initialize(Dict constraintAnnotation) {
		type = constraintAnnotation.type();
    }
	
	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		if(StrUtil.isBlank(type) || ObjectUtil.isNull(value)) {
			return false;
		}
		List<DictVal> dictList = SpringUtils.getBean(DictValCache.class).findDictData(type);
		if(CollectionUtil.isEmpty(dictList)) {
			return false;
		}
		List<String> valueList = dictList.stream().map(DictVal::getDictValue).collect(Collectors.toList());
		return valueList.contains(String.valueOf(value));
	}

}
